package com.gisocn.onemap.presenter;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import com.gisocn.onemap.base.BasePresenter;
import com.gisocn.onemap.base.Constant;
import com.gisocn.onemap.interfaces.DownLoadListener;
import com.gisocn.onemap.model.Download;
import com.gisocn.onemap.model.LoadResponseHead;
import com.gisocn.onemap.model.TreePoint;
import com.gisocn.onemap.utils.ExecutorsManager;
import com.gisocn.onemap.utils.FileUtils;
import com.gisocn.onemap.utils.L;
import com.gisocn.onemap.utils.SpUtils;
import com.gisocn.onemap.view.OfflineDownloadView;
import com.sangfor.kevinsawicki.http.HttpRequest;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

/* loaded from: classes2.dex */
public class OfflineDownloadPresenter extends BasePresenter<OfflineDownloadView> {
    private static Context context;
    private final String DOWNLOAD_PATH;
    HttpURLConnection conn;
    private boolean isZip;
    String savaFileName;
    private ArrayList<HttpURLConnection> conns = new ArrayList<>();
    private URL url = null;
    private int i = 0;
    String filePathName2 = "/storage/emulated/0/Android/data/com.gisocn.onemap/files/offline_download/shp/矢量数据2.zip";

    public void stop() {
    }

    public OfflineDownloadPresenter(OfflineDownloadView offlineDownloadView, Context context2) {
        context = context2;
        this.DOWNLOAD_PATH = Constant.SAVE_PATH;
        attachView(offlineDownloadView);
    }

    public void getDownLoadInfo(final String str, final int i) {
        ExecutorsManager.getInstance().execute(new Runnable() { // from class: com.gisocn.onemap.presenter.OfflineDownloadPresenter.1
            @Override // java.lang.Runnable
            public void run() {
                String str2;
                try {
                    try {
                        str2 = new URI(str).toASCIIString();
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                        str2 = "";
                    }
                    OfflineDownloadPresenter.this.url = new URL((str2 == null || TextUtils.isEmpty(str2)) ? "http://172.16.0.21:8080/download/.tpk" : "http://172.16.0.21:8080/download/.tpk");
                    try {
                        HttpURLConnection httpURLConnection = (HttpURLConnection) OfflineDownloadPresenter.this.url.openConnection();
                        Set<String> keySet = httpURLConnection.getHeaderFields().keySet();
                        LoadResponseHead loadResponseHead = new LoadResponseHead();
                        for (String str3 : keySet) {
                            if (str3 != null) {
                                if (str3.equals(HttpRequest.HEADER_CONTENT_LENGTH)) {
                                    loadResponseHead.setContent_length(httpURLConnection.getHeaderField(str3) + "");
                                } else if (str3.equals(HttpRequest.HEADER_LAST_MODIFIED)) {
                                    loadResponseHead.setLast_modified(httpURLConnection.getHeaderField(str3) + "");
                                } else if (str3.equals("Content-Type")) {
                                    loadResponseHead.setContent_type(httpURLConnection.getHeaderField(str3) + "");
                                }
                            }
                        }
                        ((OfflineDownloadView) OfflineDownloadPresenter.this.mvpView).getDownLoadInfoSuccess(loadResponseHead, i);
                        httpURLConnection.disconnect();
                    } catch (IOException e2) {
                        Log.e("IOException____________", e2.getMessage());
                        e2.printStackTrace();
                    }
                } catch (MalformedURLException e3) {
                    e3.printStackTrace();
                }
            }
        });
    }

    public void getDownLoading(final String str, final DownLoadListener downLoadListener) {
        L.e("getDownLoading", str);
        ExecutorsManager.getInstance().execute(new Runnable() { // from class: com.gisocn.onemap.presenter.OfflineDownloadPresenter.2
            @Override // java.lang.Runnable
            public void run() {
                String str2;
                String str3;
                boolean z;
                long j;
                boolean z2;
                try {
                    try {
                        str2 = new URI(str).toASCIIString();
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                        str2 = "";
                    }
                    OfflineDownloadPresenter.this.url = new URL(str2);
                    try {
                        HttpURLConnection httpURLConnection = (HttpURLConnection) OfflineDownloadPresenter.this.url.openConnection();
                        httpURLConnection.setRequestMethod("GET");
                        OfflineDownloadPresenter.this.conns.add(httpURLConnection);
                        httpURLConnection.setRequestProperty(HttpRequest.HEADER_ACCEPT_ENCODING, "identity");
                        File file = new File(OfflineDownloadPresenter.this.DOWNLOAD_PATH);
                        if (!file.exists()) {
                            file.mkdirs();
                        }
                        String str4 = str.split("/")[str.split("/").length - 1];
                        if (str4.substring(str4.length() - 3, str4.length()).trim().equals("tpk")) {
                            File file2 = new File(OfflineDownloadPresenter.this.DOWNLOAD_PATH + "tpk/");
                            if (!file2.exists()) {
                                file2.mkdirs();
                            }
                            str3 = OfflineDownloadPresenter.this.DOWNLOAD_PATH + "tpk/" + str4;
                            L.e("savaFileName" + str3);
                            z = false;
                        } else {
                            File file3 = new File(Constant.SAVE_PATH_SHP);
                            if (!file3.exists()) {
                                file3.mkdirs();
                            }
                            str3 = Constant.SAVE_PATH_SHP + str4;
                            z = true;
                        }
                        String str5 = str3 + ".temp";
                        File file4 = new File(str5);
                        if (file4.exists()) {
                            j = file4.length();
                            L.e("存在临时文件");
                        } else {
                            j = 0;
                        }
                        if (j != 0) {
                            httpURLConnection.setReadTimeout(6000);
                            httpURLConnection.setRequestProperty("Range", "bytes=" + j + "-");
                            httpURLConnection.connect();
                        }
                        downLoadListener.onStart();
                        L.e("haveDownLength" + j);
                        try {
                            long contentLength = httpURLConnection.getContentLength();
                            if (contentLength == -1 && httpURLConnection.getHeaderField(HttpRequest.HEADER_CONTENT_LENGTH) != null) {
                                contentLength = Long.parseLong(httpURLConnection.getHeaderField(HttpRequest.HEADER_CONTENT_LENGTH));
                            }
                            Log.e("totalLength_11111", "" + contentLength);
                            if (contentLength != 0 && contentLength != -1) {
                                long j2 = contentLength + j;
                                InputStream inputStream = httpURLConnection.getInputStream();
                                FileOutputStream fileOutputStream = new FileOutputStream(str5, j > 0);
                                L.e("____totalLength" + j2 + "1111");
                                L.e("totalLength____" + j2 + "222");
                                byte[] bArr = new byte[1048576];
                                while (true) {
                                    int read = inputStream.read(bArr);
                                    z2 = z;
                                    if (read == -1) {
                                        break;
                                    }
                                    HttpURLConnection httpURLConnection2 = httpURLConnection;
                                    String str6 = str5;
                                    long j3 = j + read;
                                    fileOutputStream.write(bArr, 0, read);
                                    DownLoadListener downLoadListener2 = downLoadListener;
                                    byte[] bArr2 = bArr;
                                    double d = j3;
                                    Double.isNaN(d);
                                    double d2 = j2;
                                    Double.isNaN(d2);
                                    long j4 = j2;
                                    downLoadListener2.onProgress((int) (((1.0d * d) / d2) * 100.0d));
                                    Double.isNaN(d);
                                    Double.isNaN(d2);
                                    if (((int) ((d * 100.0d) / d2)) == 100) {
                                        downLoadListener.onFinish(str3);
                                        Log.e("savaFileName-------", "" + str3);
                                    }
                                    httpURLConnection = httpURLConnection2;
                                    bArr = bArr2;
                                    z = z2;
                                    str5 = str6;
                                    j = j3;
                                    j2 = j4;
                                }
                                String str7 = str5;
                                fileOutputStream.flush();
                                inputStream.close();
                                fileOutputStream.close();
                                httpURLConnection.disconnect();
                                int indexOf = str7.indexOf(".temp");
                                if (indexOf >= 1) {
                                    str7.substring(0, indexOf);
                                    File file5 = new File(str7);
                                    File file6 = new File(str3);
                                    if (file6.exists()) {
                                        file6.delete();
                                        file6.createNewFile();
                                        file6.setLastModified(System.currentTimeMillis());
                                    }
                                    file5.setLastModified(System.currentTimeMillis());
                                    file5.renameTo(file6);
                                    File file7 = new File(str3);
                                    if (file7.exists()) {
                                        file7.setLastModified(System.currentTimeMillis());
                                        L.e(file7.getName() + "" + file7.lastModified());
                                    }
                                }
                                if (z2) {
                                    File file8 = new File(Constant.SAVE_PATH_SHP);
                                    if (file8.exists() && file8.listFiles().length > 0) {
                                        FileUtils.deleteDir(file8);
                                    }
                                    OfflineDownloadPresenter.this.unZipFile(str3, Constant.SAVE_PATH_SHP);
                                }
                                ((OfflineDownloadView) OfflineDownloadPresenter.this.mvpView).getDownLoadSuccess(str3, indexOf);
                                return;
                            }
                            Log.e("totalLength", "" + contentLength);
                            downLoadListener.onFailure();
                            httpURLConnection.disconnect();
                        } catch (FileNotFoundException e2) {
                            e2.printStackTrace();
                        } catch (IOException e3) {
                            e3.printStackTrace();
                        }
                    } catch (IOException e4) {
                        e4.printStackTrace();
                    }
                } catch (MalformedURLException e5) {
                    e5.printStackTrace();
                }
            }
        });
    }

    public void transFileEncoding(String str) throws IOException {
        Log.e("filePathName", str);
        Log.e("filePathName2", this.filePathName2);
        InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(str), "GBK");
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(this.filePathName2), "UTF-8");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        while (true) {
            String readLine = bufferedReader.readLine();
            if (readLine != null) {
                outputStreamWriter.write(readLine + '\n');
            } else {
                inputStreamReader.close();
                outputStreamWriter.close();
                bufferedReader.close();
                return;
            }
        }
    }

    public void deFile(String str) {
        File file = new File(str);
        File file2 = new File(str + "2");
        File file3 = new File(str);
        file.delete();
        file2.renameTo(file3);
    }

    public void deleteDir(File file) {
        L.e("删除整个文件夹file" + file.getAbsolutePath());
        if (file.exists()) {
            if (file.isDirectory()) {
                File[] listFiles = file.listFiles();
                if (listFiles == null || listFiles.length == 0) {
                    file.delete();
                }
                for (File file2 : listFiles) {
                    deleteDir(file2);
                }
            }
            file.delete();
        }
    }

    public void unZip(String str, String str2, String str3) {
        ZipInputStream zipInputStream;
        SpUtils.put(context, "savaFileName", str);
        new File(str3);
        try {
            zipInputStream = new ZipInputStream(new BufferedInputStream(new FileInputStream(str)));
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        while (true) {
            ZipEntry nextEntry = zipInputStream.getNextEntry();
            if (nextEntry != null) {
                try {
                    Log.i("Unzip: ", "=" + nextEntry);
                    byte[] bArr = new byte[4096];
                    String name = nextEntry.getName();
                    File file = new File(str2 + name);
                    File file2 = new File(file.getParent());
                    if (!file2.exists()) {
                        file2.mkdirs();
                    }
                    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file), 4096);
                    while (true) {
                        int read = zipInputStream.read(bArr, 0, 4096);
                        if (read == -1) {
                            break;
                        }
                        bufferedOutputStream.write(bArr, 0, read);
                    }
                    bufferedOutputStream.flush();
                    bufferedOutputStream.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                    L.e("解压失败" + e2.getMessage());
                }
            } else {
                zipInputStream.close();
                L.e("解压完成" + str3);
                deleteDir(new File(str3));
                return;
            }
            e.printStackTrace();
            return;
        }
    }

    public void unZipFile(String str, String str2) {
        L.e("开始解压" + str);
        if (new File(str).exists()) {
            try {
                ZipFile zipFile = new ZipFile(str, Charset.forName("GBK"));
                Enumeration<? extends ZipEntry> entries = zipFile.entries();
                while (entries.hasMoreElements()) {
                    ZipEntry nextElement = entries.nextElement();
                    String name = nextElement.getName();
                    File file = new File(new File(str2 + name).getParent());
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(str2 + "/" + name));
                    BufferedInputStream bufferedInputStream = new BufferedInputStream(zipFile.getInputStream(nextElement));
                    byte[] bArr = new byte[4096];
                    for (int read = bufferedInputStream.read(bArr); read != -1; read = bufferedInputStream.read(bArr)) {
                        bufferedOutputStream.write(bArr, 0, read);
                    }
                    bufferedOutputStream.close();
                }
                zipFile.close();
                L.e("解压完成" + str);
                deleteDir(new File(str));
            } catch (IOException e) {
                L.e("解压失败" + e.getMessage());
            }
        }
    }

    public void closeDownloading() {
        Iterator<HttpURLConnection> it = this.conns.iterator();
        while (it.hasNext()) {
            it.next().disconnect();
        }
        this.conns.clear();
    }

    public ArrayList<File> getLocalPathFile(String str, ArrayList<File> arrayList) {
        if (arrayList == null) {
            arrayList = new ArrayList<>();
        }
        File[] listFiles = new File(str).listFiles();
        if (listFiles == null) {
            return arrayList;
        }
        for (int i = 0; i < listFiles.length; i++) {
            if (listFiles[i].isDirectory()) {
                getLocalPathFile(listFiles[i].getAbsolutePath(), arrayList);
            } else {
                arrayList.add(listFiles[i]);
            }
        }
        return arrayList;
    }

    public int getUpdateCountsFist(ArrayList<Download.NewItem> arrayList) {
        Iterator<Download.NewItem> it = arrayList.iterator();
        int i = 0;
        while (it.hasNext()) {
            Download.NewItem next = it.next();
            if (next.getItems() != null && next.getItems().size() > 0) {
                for (int i2 = 0; i2 < next.getItems().size(); i2++) {
                    i = getCountRes(next.getItems().get(i2).getVersionDesc(), i);
                }
            } else {
                i = getCountRes(next.getVersionDesc(), i);
            }
        }
        return i;
    }

    public int getUpdateCounts(ArrayList<TreePoint> arrayList) {
        int i = 0;
        for (int i2 = 0; i2 < arrayList.size(); i2++) {
            if ("1".equals(arrayList.get(i2).getISLEAF())) {
                i = getCountRes(arrayList.get(i2).getVersionDesc(), i);
            }
        }
        return i;
    }

    public int getCountRes(String str, int i) {
        return (TextUtils.isEmpty(str) || str.equals("已是最新版本")) ? i : i + 1;
    }

    public int getUpdateCountsChild(ArrayList<Download.NewItem> arrayList, int i, int i2) {
        return !arrayList.get(i).getItems().get(i2).getVersionDesc().equals("已完成") ? 1 : 0;
    }
}
